//
//  CycleScrollView.m
//  116114
//
//  Created by 潘超 on 13-7-23.
//  Copyright (c) 2013年 Raiyi. All rights reserved.
//

#import "CycleScrollView.h"
#import <QuartzCore/QuartzCore.h>
@implementation CycleScrollView

@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;
@synthesize currentPage = _curPage;
@synthesize datasource = _datasource;
@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect)frame withPageControlStyle:(int)type withPageControlFrame:(CGRect)pFrame addSubViewToView:(UIView *) sView
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, self.bounds.size.height);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
        _scrollView.pagingEnabled = YES;
        [self addSubview:_scrollView];
        [self setPageControlStyle:type andFrame:pFrame];
        _curPage = 0;
        [sView addSubview:self];
    }
    return self;
}

-(void) setViewFrame:(CGRect)frame
{
    self.frame = frame;
    self.scrollView.frame =frame;
}

-(void) setPageControlStyle:(int)type andFrame:(CGRect)frame{
    pageControlType=type;
    switch (type) {
        case PageControlTypeDefault:
        {
            _pageControl = [[UIPageControl alloc] initWithFrame:frame];
            _pageControl.userInteractionEnabled = NO;
            [self addSubview:_pageControl];
        }
            break;
        case PageControlTypeSlider:
        {
            //Add:潘超 2013-07-23	sliderPageControl
            self.sliderPageControl = [[SliderPageControl  alloc] initWithFrame:frame setBackgroud:[UIColor whiteColor] setpointColor:[UIColor colorWithRed:86/255.0   green:189/255.0 blue:254/255.0 alpha:1]];
            [self.sliderPageControl addTarget:self action:@selector(onPageChanged:) forControlEvents:UIControlEventValueChanged];
            [self.sliderPageControl setDelegate:self];
            [self.sliderPageControl setShowsHint:NO];
            [self addSubview:self.sliderPageControl];
            [self.sliderPageControl setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            //End
        }
            
        default:
            break;
    }
}

- (void)setDataource:(id<CycleScrollViewDatasource>)datasource
{
    _datasource = datasource;
    [self reloadData];
}

- (void)reloadData
{
    if (self.superview == nil) {
//        EXPORTLOG(DEBUG_DEBUG, @"cycleScrollView reloadData superview is %@",self.superview);
        return;
    }
    _totalPages = [_datasource numberOfPagesAt:self];
    if (_totalPages == 0) {
        return;
    }
    switch (pageControlType) {
        case PageControlTypeDefault:
            _pageControl.numberOfPages = _totalPages;
            break;
        case PageControlTypeSlider:
        {
            if (_totalPages>1) {
                _sliderPageControl.alpha = 1;
            }
            else{
                _sliderPageControl.alpha = 0;
            }
            _sliderPageControl.numberOfPages=_totalPages;
        }
            break;
            
        default:
            break;
    }
    [self loadData];
}
-(void) startAutoScroll:(NSTimeInterval) time{
    if (self.superview == nil) {
//        EXPORTLOG(DEBUG_DEBUG, @"cycleScrollView superview startAutoScroll is %@",self.superview);
        [self stopAutoScroll];
        return;
    }
    [self stopAutoScroll];
    if (_totalPages>1) {
        _scrollView.scrollEnabled = YES;
        _timer  =[NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(autoScrollView:) userInfo:nil repeats:YES];
    }else{
        _scrollView.scrollEnabled = NO;
    }
}
-(void) stopAutoScroll{
    [_timer invalidate];
    _timer = nil;
}
-(BOOL) isAutoScroll{
    return [_timer isValid];
}
-(void) autoScrollView:(NSTimer *) sender{
    if (self.superview == nil) {
//        EXPORTLOG(DEBUG_DEBUG, @"cycleScrollView superview autoScrollView is %@",self.superview);
        [self stopAutoScroll];
        return;
    }
    _curPage = [self validPageValue:_curPage+1];
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.35f];
    [animation setType:kCATransitionMoveIn];
    [animation setSubtype:kCATransitionFromRight];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self loadData];
    //Modify:潘超 2013-07-29	修改view动画为ScrollView动画
    [self.scrollView.layer addAnimation:animation forKey:nil];
//End

}

- (void)loadData
{
    //Add:潘超 2013-07-23	切换城市时候，会导致当前页大于总数，并Crash
    if (_curPage >= _totalPages || _curPage < 0) {
//        EXPORTLOG(DEBUG_DEBUG, @"curPage = %d ,totalPages = %d",_curPage,_totalPages);
        _curPage = 0;
    }
    //End
    switch (pageControlType) {
        case PageControlTypeDefault:
            _pageControl.currentPage = _curPage;
            break;
        case PageControlTypeSlider:
        {
            [_sliderPageControl setCurrentPage:_curPage animated:NO];
        }
            break;
        default:
            break;
    }
    
    //从scrollView上移除所有的subview
    NSArray *subViews = [_scrollView subviews];
    if([subViews count] != 0) {
        [subViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    if (_totalPages==1&&_curPage==0) {
        UIView *view = [_datasource cycleScrollView:self pageAtIndex:_curPage];
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(handleTap:)];
        [view addGestureRecognizer:singleTap];
        view.frame = CGRectOffset(view.frame, 320, 0);
        [_scrollView addSubview:view];
    }
    else
    {
        [self getDisplayImagesWithCurpage:_curPage];
        
        for (int i = 0; i < 3; i++) {
            UIView *view = [_curViews objectAtIndex:i];
            view.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                        action:@selector(handleTap:)];
            [view addGestureRecognizer:singleTap];
            view.frame = CGRectOffset(view.frame, view.frame.size.width * i, 0);
            [_scrollView addSubview:view];
        }
    }
    
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
}

- (void)getDisplayImagesWithCurpage:(int)page {
    int pre = [self validPageValue:_curPage-1];
    int last = [self validPageValue:_curPage+1];
    if (!_curViews) {
        _curViews = [[NSMutableArray alloc] init];
    }
    
    [_curViews removeAllObjects];

    [_curViews addObject:[_datasource cycleScrollView:self pageAtIndex:pre]];
    [_curViews addObject:[_datasource cycleScrollView:self pageAtIndex:page]];
    [_curViews addObject:[_datasource cycleScrollView:self pageAtIndex:last]];
}

- (int)validPageValue:(NSInteger)value {
    
    if(value == -1) value = _totalPages - 1;
    if(value == _totalPages) value = 0;
    
    return value;
    
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    
    if ([_delegate respondsToSelector:@selector(didClickPage:atIndex:)]) {
        [_delegate didClickPage:self atIndex:_curPage];
    }
    
}

- (void)setViewContent:(UIView *)view atIndex:(NSInteger)index
{
    if (index == _curPage) {
        [_curViews replaceObjectAtIndex:1 withObject:view];
        for (int i = 0; i < 3; i++) {
            UIView *view = [_curViews objectAtIndex:i];
            view.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                        action:@selector(handleTap:)];
            [view addGestureRecognizer:singleTap];
            view.frame = CGRectOffset(view.frame, view.frame.size.width * i, 0);
            [_scrollView addSubview:view];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    int x = aScrollView.contentOffset.x;
    
    //往下翻一张
    if(x >= (2*self.frame.size.width)) {
        _curPage = [self validPageValue:_curPage+1];
        [self loadData];
    }
    
    //往上翻
    if(x <= 0) {
        _curPage = [self validPageValue:_curPage-1];
        [self loadData];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView {
    
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0) animated:YES];
    [self stopAutoScroll];
}

//Add:潘超 2013-07-23	slideerPageControl
#pragma mark sliderPageControlDelegate
- (NSString *)sliderPageController:(id)controller hintTitleForPage:(NSInteger)page
{
	NSString *hintTitle = @"";
	return hintTitle;
}
- (void)onPageChanged:(id)sender
{
    [self stopAutoScroll];
	[self slideToCurrentPage:YES];
}
- (void)slideToCurrentPage:(bool)animated
{
    _curPage = [self validPageValue:_sliderPageControl.currentPage];
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.35f];
    [animation setType:kCATransitionFade];
    [animation setSubtype:kCATransitionFromRight];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self loadData];
    [self.layer addAnimation:animation forKey:nil];
}
- (void)changeToPage:(int)page animated:(BOOL)animated
{
	[_sliderPageControl setCurrentPage:page animated:YES];
	[self slideToCurrentPage:animated];
}
//End
@end
